package cn.wygandwdn.learn.aop_test;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.springframework.aop.Advisor;
import org.springframework.aop.Pointcut;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.NameMatchMethodPointcutAdvisor;
import org.springframework.util.StopWatch;

/**
 * @description:
 * @author: WYG
 * @time: 2021/5/9 17:03
 */

public class UseProxyFactory {
    static interface ITask {
        void execute();
    }
    static class MockTask implements ITask {
        @Override
        public void execute() {
            System.out.println("task executed!");
        }
    }

    static class Executable {
        public void execute() {
            System.out.println("task executed!");
        }
    }

    static class PerformanceMethodInterceptor implements MethodInterceptor {
        private final Log logger = LogFactory.getLog(UseProxyFactory.class);
        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            StopWatch watch = new StopWatch();
            try {
                watch.start();
                return invocation.proceed();
            } finally {
                watch.stop();
                if (logger.isInfoEnabled()) {
                    logger.info(watch.toString());
                }
            }

        }
    }

    public static void main(String[] args) {
        /*MockTask mockTask = new MockTask();
        ProxyFactory weaver = new ProxyFactory(mockTask);
        NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor();
        advisor.setMappedName("execute");
        advisor.setAdvice(new PerformanceMethodInterceptor());
        weaver.addAdvisor(advisor);
        System.out.println(weaver.getProxy().getClass());
        ITask task = (ITask) weaver.getProxy();
        task.execute();*/
        ProxyFactory weaver = new ProxyFactory(new Executable());
        NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor();
        advisor.setMappedName("execute");
        advisor.setAdvice(new PerformanceMethodInterceptor());
        weaver.addAdvisor(advisor);
        Executable proxy = (Executable) weaver.getProxy();
        proxy.execute();
        System.out.println(proxy.getClass());
    }
}
